from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from .models import Restaurant, MenuItem, Order, OrderItem
from django.contrib import messages

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, '注册成功！')
            return redirect('home')
    return render(request, 'registration/register.html')

def home(request):
    restaurants = Restaurant.objects.all()
    return render(request, 'orders/home.html', {'restaurants': restaurants})

def restaurant_detail(request, restaurant_id):
    restaurant = Restaurant.objects.get(pk=restaurant_id)
    menu_items = MenuItem.objects.filter(restaurant=restaurant, is_available=True)
    return render(request, 'orders/restaurant_detail.html', {
        'restaurant': restaurant,
        'menu_items': menu_items
    })

@login_required
def order_create(request, restaurant_id):
    if request.method == 'POST':
        restaurant = Restaurant.objects.get(pk=restaurant_id)
        order = Order.objects.create(
            customer=request.user,
            restaurant=restaurant,
            total_amount=0,
            delivery_address=request.POST.get('delivery_address')
        )
        
        total = 0
        for item_id, quantity in request.POST.items():
            if item_id.startswith('item_'):
                if quantity and int(quantity) > 0:
                    menu_item = MenuItem.objects.get(pk=int(item_id.split('_')[1]))
                    OrderItem.objects.create(
                        order=order,
                        menu_item=menu_item,
                        quantity=int(quantity),
                        price=menu_item.price
                    )
                    total += menu_item.price * int(quantity)
        
        order.total_amount = total
        order.save()
        messages.success(request, '订单创建成功！')
        return redirect('order_detail', order_id=order.id)
    
    return redirect('restaurant_detail', restaurant_id=restaurant_id)

@login_required
def order_list(request):
    orders = Order.objects.filter(customer=request.user).order_by('-created_at')
    return render(request, 'orders/order_list.html', {'orders': orders})

@login_required
def order_detail(request, order_id):
    order = Order.objects.get(pk=order_id, customer=request.user)
    return render(request, 'orders/order_detail.html', {'order': order})